package com.bigfreakindeals.Activities;


import java.util.ArrayList;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.GPSController;
import com.bigfreakindeals.Controller.GPSLocationListener;
import com.bigfreakindeals.Models.UserProfile;
import com.bigfreakindeals.Protocols.SoapHandlers.ClosestSchoolHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.FAQHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.GetSchoolListHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.LoginHandler;
import com.bigfreakindeals.Widgets.AlertManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Toast;



public class SplashScreenActivity extends BaseActivity{
Double currentLatitude;
Toast toast;
Double currentLongitude;
public static final String PREFS_NAME = "MyPrefsFile";

Location location;
		 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		
		System.out.println("Splash Step 1");
		Display display = getWindowManager().getDefaultDisplay(); 
		
		ApplicationEx.getInstance().screenWidth	= display.getWidth();
		ApplicationEx.getInstance().screenHeight = display.getHeight();
		setContentView(R.layout.splashscreen);
		
		LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		String provider = locationManager.getBestProvider(criteria, false);
		location = locationManager.getLastKnownLocation(provider);
		System.out.println("Splash Step 2");
		if (isAutoLogin()){ //isAutoLogin();	
		
			signIn(ApplicationEx.getInstance().myProfile.getUsername(),ApplicationEx.getInstance().myProfile.getPassword());
			
		}else if (location!=null )	{
			
			currentLatitude = location.getLatitude();
			currentLongitude = location.getLongitude();
			if (ApplicationEx.getInstance().myProfile==null)
				ApplicationEx.getInstance().myProfile = new UserProfile();
			ApplicationEx.getInstance().myProfile.university_preference_Lat = ""+currentLatitude;
			ApplicationEx.getInstance().myProfile.university_preference_Long= ""+currentLongitude;
			ApplicationEx.getInstance().controller.getClosestSchool(this,true);
			
		}else {
			//showtoast(false,currentLongitude, currentLatitude);
			ApplicationEx.getInstance().controller.getClosestSchool(this,false);
			
		}
			
	 	this.registerReceiver(broadcastreceiver, new IntentFilter(Constant.EVENTS_LOGINERROR));
	 	this.registerReceiver(broadcastreceiver, new IntentFilter(Constant.EVENTS_LOGINSUCCESS));
	 	
	}	
	public BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			ApplicationEx.getInstance().progressDialog.dismiss();
			if (intent.getAction().equals(Constant.EVENTS_LOGINERROR)) {
			   	// DO the following:
			   	//Display error message as alert
			   	// retunr back to login screen
			   	
				String errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
			   	displayErrorMessage(errormessage);
			   	
			}else if (intent.getAction().equals(Constant.EVENTS_LOGINSUCCESS)) {
			   
				// DO the following:
			   	// get users university info( must be do in the loginhandler)
			   	// exit login page and go to the active deals screen(MainTabActivity State= activedeals);
			   	savePreferences();
			 	displayLoginSuccess();
			   	
			}
			}
	};
	private void  savePreferences(){
	 	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    SharedPreferences.Editor editor = settings.edit();
	      editor.putString("username", ApplicationEx.getInstance().myProfile.getUsername());
	      editor.putString("password", ApplicationEx.getInstance().myProfile.getPassword());
	      editor.putString("email", ApplicationEx.getInstance().myProfile.getEmail());

	      
	      editor.putBoolean("rememberme", ApplicationEx.getInstance().myProfile.isSettings_rememberMe());
	      editor.putBoolean("newdeals", ApplicationEx.getInstance().myProfile.isSettins_notificationNewDeals());
	      editor.putBoolean("beansays", ApplicationEx.getInstance().myProfile.isSettins_notificationbeanSays());
	      editor.commit();
	}
public void displayErrorMessage(String errorMessage){
		
		AlertManager.alertOK(this,errorMessage, "OK");
		 if (location!=null )	{
				
				currentLatitude = location.getLatitude();
				currentLongitude = location.getLongitude();
				if (ApplicationEx.getInstance().myProfile==null)
					ApplicationEx.getInstance().myProfile = new UserProfile();
				ApplicationEx.getInstance().myProfile.university_preference_Lat = ""+currentLatitude;
				ApplicationEx.getInstance().myProfile.university_preference_Long= ""+currentLongitude;
				ApplicationEx.getInstance().controller.getClosestSchool(this,true);
				
			}else {
				//showtoast(false,currentLongitude, currentLatitude);
				ApplicationEx.getInstance().controller.getClosestSchool(this,false);
				
		}
		
	}
	public void displayLoginSuccess(){
	 
	
	
	
			new Thread() {
				@Override
				public void run(){
					try {
						sleep(1000);
					} catch (Exception e) {
					}
				} 
			}.start();
		
			ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Login successful", "please wait...");
			ApplicationEx.getInstance().controller.getClosestSchool(this,false);
		
		
	
	}
	private void signIn(String email, String password) {
		// TODO Auto-generated method stub
		 ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Login", "Please wait...");
	       
		final ArrayList<String> params = new ArrayList<String>();
		params.add(email);
		params.add(password);
		final Context context =this;
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new LoginHandler(Tools.getURL(Constant.GET_LOGIN, params ),context);
				
			}

		}.start();
		
	}
	
	public void showProgress(){
				
        	
	}
	@Override
	public void onResume() {
		super.onResume();
		
		//getLocation();
	} 
	@Override
	public void onDestroy(){
		this.unregisterReceiver(broadcastreceiver);
		super.onDestroy();	
	}
	@Override
	public void onPause(){
		super.onPause();
		//toast.cancel();
	}
	 private boolean isAutoLogin(){
		  try{
			 String PREFS_NAME = "MyPrefsFile";
		  

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			if (ApplicationEx.getInstance().myProfile ==null){
				ApplicationEx.getInstance().myProfile = new UserProfile();
			}
			ApplicationEx.getInstance().myProfile.setUsername(settings.getString("username", null));
			ApplicationEx.getInstance().myProfile.setEmail(settings.getString("email", null));
			ApplicationEx.getInstance().myProfile.setPassword(settings.getString("password", null));
		    
			boolean isSettings = settings.getBoolean("rememberme", true);
			boolean newdeals = settings.getBoolean("newdeals", true);
			boolean beansay = settings.getBoolean("beansays", true);
		
			
			ApplicationEx.getInstance().myProfile.setSettings_rememberMe(isSettings?1:0);
			ApplicationEx.getInstance().myProfile.setSettins_notificationbeanSays((beansay?1:0));
			ApplicationEx.getInstance().myProfile.setSettins_notificationNewDeals((newdeals?1:0));
			if ( ApplicationEx.getInstance().myProfile.getUsername()!=null && 
					ApplicationEx.getInstance().myProfile.getPassword()!=null)
			return isSettings;
			
		  }catch (Exception e) {
			// TODO: handle exception
		}  
		 return false;	
	 }
	
	
		/*public void showtoast(boolean isSuccess, Double longitude, Double latitude){
			try{
				toast = Toast.makeText(this,isSuccess==true?("location acquired: \nlongitude: "+longitude+"\n latitude: "+latitude+" \n\nGetting nearest school.."):"location cannot be acquired; defaulting to univ-washington", 20000);
				toast.show();
			}catch (Exception e) {
				// TODO: handle exception
			}
			
		}*/
	
}
